package edu.xmut.yuepai.gateway.utils;

import com.alibaba.fastjson.JSON;
import edu.xmut.yuepai.common.result.R;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

public class MonoUtils {
    public static Mono<Void> setResponse(ServerWebExchange exchange, Integer code, String message) {
        ServerHttpResponse response = exchange.getResponse();
        byte[] bytes = JSON.toJSONString(R.fail(code, message)).getBytes(StandardCharsets.UTF_8);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }
}
